/*
 * @Descripttion: 腾讯云COS文件上传
 * @Author: liuxiaoling
 * @Date: 2022-02-17 02:12:05
 */
import api from '../api/'
import {v4 as uuidv4} from 'uuid'
import COS from 'cos-js-sdk-v5'

const Bucket = 'jinpin-1304985105' // 存储桶名称
const Region = 'ap-guangzhou' // 存储桶地域
const RootFolder = '/image' // 根目录

const cos = new COS({
  // getAuthorization 必选参数
  getAuthorization(options, callback) {
    api.config.getCosToken().then(res => {
      if (res.code == 200 && res.data) {
        try {
          let data = res.data
          let credentials = data.credentials
          if (!data || !credentials) {
            console.error('credentials invalid:\n' + res.data)
            callback('获取签名出错')
          }
          callback({
            TmpSecretId: credentials.TmpSecretId,
            TmpSecretKey: credentials.TmpSecretKey,
            SecurityToken: credentials.Token,
            StartTime: data.startTime, // 时间戳，单位秒，如：1580000000
            ExpiredTime: data.expiredTime // 时间戳，单位秒，如：1580000000
          })
        } catch (e) {
          console.error(e)
          callback('获取签名出错')
        }
      } else {
        callback('获取签名出错')
      }
    })
  }
})

export function cosUploadImg(file, imgType) {
  return new Promise((resolve, reject) => {
    uploadImg(file, imgType, res => {
      if (res.success) {
        resolve({code: 200, data: res.data})
      }
      resolve({code: -1, data: null})
    })
  })
}

function uploadImg(file, imgType, callback) {
  if (!file) {
    return null
  }
  // 处理文件名称路径
  let temporary = file.name.lastIndexOf('.')
  let fileNameLength = file.name.length
  let fileFormat = file.name.substring(temporary + 1, fileNameLength)
  // 文件路径和文件名
  let filePath = RootFolder + (imgType ? '/' + imgType : '') + genDatePath() + genUUID() + '.' + fileFormat

  cos.putObject(
    {
      Bucket: Bucket, // 存储桶名称
      Region: Region, // 存储桶地址
      Key: filePath, // 文件路径和文件名
      StorageClass: 'STANDARD',
      // 上传文件对象
      Body: file,
      onProgress: progressData => {
        // console.log(`log- progressData: ${JSON.stringify(progressData)}`)
      }
    },
    (err, data) => {
      // console.log(`log- upload data: ${JSON.stringify(data)} ｜ err: ${JSON.stringify(err)}`)
      if (data && data.statusCode === 200) {
        //　文件上传成功后填充
        // 自定义CDN域名
        // let uploadResult = 'https://static.files.xxxxxxx.cn' + filePath
        // 未使用自定义CDN域名
        let uploadResult = `https://${data.Location}`
        // callback({success: false, msg: '上传失败!', data: null})
        callback({success: true, msg: '上传成功!', data: uploadResult})
      } else {
        callback({success: false, msg: '上传失败!', data: null})
        return
      }
    }
  )
}

/**
 * 生产一个UUID
 */
function genUUID() {
  return uuidv4()
}

/**
 * 根据当前时间年月日生成一个文件路径
 * @returns 例：'/2022/2/17/'
 */
function genDatePath() {
  let date = new Date()
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()

  return `/${year}/${month}/${day}/`
}
